import { LOGIN_STATUS } from "@/config/cache";
import { getCurlOauth, getOpenidByCode } from "@/api/user";
import { useTokenStore } from "@/store/index";
import Cache from "@/utils/cache";
async function setWechatToken(redirect_url: string) {
  const token = Cache.get(LOGIN_STATUS);

  var url = window.location.href;
  var theRequest: Record<string, string> = {};
  if (url.indexOf("?") != -1) {
    var str = url.substr(url.indexOf("?") + 1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }
  if (theRequest.code) {
    // 存在code时，调用接口获取token
    // 使用code和state调用接口获取普通用户的token
    let res = await getOpenidByCode({
      code: theRequest.code,
      state: theRequest.state,
    });
    let { data, code, info } = res;
    let token = data.token.token;
    const tokenStore = useTokenStore();
    await tokenStore.setToken(token);
    return;
  }
  if (!token) {
    getCurlOauthHandler(redirect_url);
  }
}
// 获取公众号授权链接并跳转
async function getCurlOauthHandler(url: string) {
  let redirect_url = url;
  if (Cache.get("business_id")) {
    redirect_url += `?business_id=${Cache.get("business_id")}`;
  }
  if (Cache.get("urltype")) {
    redirect_url += `&urltype=${Cache.get("urltype")}`;
  }
  let params = { mode: 0, source: redirect_url };
  let res = await getCurlOauth(params);
  let { auth_url } = res.data;
  window.location = auth_url;
}
export default setWechatToken;
